package com.dawnClass.interceptor;


import com.dawnClass.util.ServiceResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("TimeInterceptor 进入 Controller 某个方法之前");
        StringBuffer controllerName = null;
        try {
            controllerName = new StringBuffer(((HandlerMethod)handler).getBean().getClass().getName());
        }catch (ClassCastException e){
            response.sendRedirect("/dawnClass/login/login.jsp");
            System.out.println("错误页面");
            return false;
        }

        System.out.println("Controller Name:" + controllerName);
        System.out.println("Controller Method Name:" + ((HandlerMethod)handler).getMethod().getName());
        request.setAttribute("startTime", new Date().getTime());

        ServiceResponse consumerResponse = (ServiceResponse) request.getSession(false).getAttribute("ServiceResponse");
        if (consumerResponse == null){
            response.sendRedirect("/dawnClass/login/login.jsp");
            System.out.println("用户未登录，拦截");
            return false;
        }else {
            System.out.println("用户已登录，放行");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("TimeInterceptor 运行 Controller 某个方法时，方法抛出异常将不进入此方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为："+ (new Date().getTime() - start));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("TimeInterceptor 完成 Controller 某个方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为："+ (new Date().getTime() - start));
    }
}
